package com.example.robolectricsample

import android.content.Intent
import android.widget.Button
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.MockitoAnnotations
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.android.controller.ActivityController
import org.robolectric.shadows.ShadowApplication
import org.robolectric.shadows.ShadowToast

@RunWith(RobolectricTestRunner::class)
class MainActivityTest {
    @Mock
    private lateinit var mainViewModel: MainViewModel
    private lateinit var mainActivityController: ActivityController<MainActivity>
    private lateinit var mainActivity: MainActivity

    @Before
    fun setUp() {
        println("run setUp")

        MockitoAnnotations.openMocks(this)

        mainActivityController = Robolectric.buildActivity(MainActivity::class.java).create()
        mainActivity = mainActivityController.get()

        mainActivity.viewModel = mainViewModel
    }

    @Test
    fun testClick() {
        val btnTest: Button = mainActivity.findViewById(R.id.btn_test)
        btnTest.performClick()

        val expectedActivity = Intent(mainActivity, SecondActivity::class.java)
        val actualIntent = ShadowApplication.getInstance().nextStartedActivity
        Assert.assertEquals(actualIntent.component, expectedActivity.component)

        Assert.assertEquals(
            mainActivity.getString(R.string.toast_text),
            ShadowToast.getTextOfLatestToast()
        )

        println("toast text:${ShadowToast.getTextOfLatestToast()}")
    }

    @Test
    fun testLoadData() {
        println("testLoadData")
        mainActivity.loadData()
        Mockito.verify(mainViewModel).fetchList()
    }

    @Test
    fun testOnResume() {
        mainActivityController.resume()
    }

    @Test
    fun testOnPause() {
        mainActivityController.pause()
    }

}